package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.contractReviewManager.ContractImportVO;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @author luojie
 * @date 2021/6/2 15:16
 */
@Slf4j
public class InsertContractCallable implements Callable<JSONObject> {

    private List<ContractImportVO> list;

    private CountDownLatch begin;

    private CountDownLatch end;

    private CustomerDbService customerDbService;

    private CustomerContractDbService customerContractDbService;

    private UserInfoDbService userInfoDbService;

    private ImportFailureLogDbService importFailureLogDbService;

    private ContactDbService contactDbService;

    private SysCompanyDbService companyDbService;

    public InsertContractCallable(List<ContractImportVO> list, CountDownLatch begin, CountDownLatch end,CustomerDbService customerDbService,CustomerContractDbService customerContractDbService,
                                  UserInfoDbService userInfoDbService,ImportFailureLogDbService importFailureLogDbService,ContactDbService contactDbService,SysCompanyDbService companyDbService){
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.customerDbService = customerDbService;
        this.customerContractDbService = customerContractDbService;
        this.userInfoDbService = userInfoDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.contactDbService = contactDbService;
        this.companyDbService = companyDbService;
    }

    @Override
    public JSONObject call() throws Exception {
        //获取登录人信息
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String operatePeopleId = userAccount.getAccountId();

        //导入数量
        int importNum = 0;
        //客户名称为空
        List<Integer> customerEmptyIdList = new ArrayList();
        //数据库客户不存在
        List<Integer> customerNotExistIdList = new ArrayList();
        //合同编号重复的行数
        List<Integer> repeatIdList = new ArrayList();
        //所有人不存在
        List<Integer> ownerEmptyIdList = new ArrayList();
        //失败行数
        List<Integer> importFailIdList = new ArrayList();
        //合同未生效行数
        List<Integer> notValidIdList = new ArrayList();

        for (int i = 0; i < list.size(); i++) {
            //合同导入VO
            ContractImportVO contractImportVO = list.get(i);
            //公司id
            String companyId = "";
            //所有人id
            String accountId = "";
            //合同编号
            String contractNumber = contractImportVO.getContractNumber();
            //客户赋默认值
            Customer customer = null;
            //是否导入失败
            String ifImportError = "0";

            //查询公司
            SysCompany sysCompany = companyDbService.selectSysCompanyByName(contractImportVO.getCompanyName());
            if(sysCompany!=null){
                companyId = sysCompany.getCompanyId();
            }
            try {
                    //查询所有人是否存在
                    UserInfo userInfo = null;
                    if(!StringUtils.isBlank(contractImportVO.getCreatePeopleId())){
                        userInfo = userInfoDbService.getUserInfoByUserNameAndCompanyName(contractImportVO.getCreatePeopleId(),contractImportVO.getCompanyName());
                        if(userInfo==null){
                            ownerEmptyIdList.add(i+2);
                            ifImportError = "1";
                            Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                            if(!result){
                                importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，所有人不存在",null,null,"3",null,null));
                            }
                            //continue;
                        }else {
                            //所有人id
                            accountId = userInfo.getAccountId();
                            //公司id
                            companyId = userInfo.getCompanyId();

                            //判断客户是否为空
                            String customerName = contractImportVO.getCustomerName();
                            if(StringUtils.isBlank(customerName)){
                                customerEmptyIdList.add(i+2);
                                ifImportError = "1";
                                Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                                if(!result){
                                    importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，客户名称为空",null,null,"3",companyId,accountId));
                                }
                                //continue;
                            }else{
                                //合同状态
                                String contractStatus = contractImportVO.getContractStatus();
                                //总回款金额
                                String contractTotalPaymentAmount = contractImportVO.getContractTotalPaymentAmount();
                                //查询合同是否生效
                                if(!"生效中".equals(contractStatus) && !(!StringUtils.isBlank(contractTotalPaymentAmount) && "已结束".equals(contractStatus))){
                                    notValidIdList.add(i+2);
                                    ifImportError = "1";
                                    Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                                    if(!result){
                                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，没有生效",null,null,"4",companyId,accountId));
                                    }
                                    //continue;
                                }else{
                                    //查询客户是否存在
                                    customer = customerDbService.selectCustomerByNameAndId(customerName,userInfo.getAccountId());
                                    if(customer==null){
                                        customerNotExistIdList.add(i+2);
                                        ifImportError = "1";
                                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                                        if(!result){
                                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，客户不存在",null,null,"3",companyId,accountId));
                                        }
                                        //continue;
                                    }else{
                                        //查询合同编号是否存在
                                        CustomerContract customerContract = customerContractDbService.selectContractByContractNumber(contractImportVO.getContractNumber());
                                        if(customerContract!=null){
                                            repeatIdList.add(i+2);
                                            ifImportError = "1";
/*                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，相同合同编号数据已经存在",customerContract.getContractId(),null,"1",companyId,accountId));
                        }*/
                                            //continue;
                                        }
                                    }
                                }
                            }

                        }
                    }else {
                        ownerEmptyIdList.add(i+2);
                        ifImportError = "1";

                        //通过业务类型（operateType）、导入名称（importName）、公司id（companyId）、所有人id（accountId）、导入的数据（importData）
                        //查询是否有重复日志
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，所有人数据为空", null, null, "3", null, null));
                        }

                        //continue;
                    }

                    CustomerContract customerContractAdd = addContractModel(contractImportVO,customer,userInfo,ifImportError);
                    Boolean insertResult = customerContractDbService.insertCustomerContract(customerContractAdd);
                    if (insertResult) {
                        //导入成功
                        importNum = importNum + 1;
                        //更新客户表——新单/续费客户类型
                        if(customer!=null){
                            Customer customerUpdate = new Customer();
                            customerUpdate.setCustomerId(customer.getCustomerId());
                            customerUpdate.setNewOrderRenewalCustomer(Integer.parseInt(customerContractAdd.getWhetherCheck()));
                            customerDbService.updateCustomerById(customerUpdate);
                        }
                    } else {
                        //导入失败
                        importFailIdList.add(i+2);
                        ifImportError = "1";
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，插入数据失败",null,null,"4",companyId,accountId));
                        }
                    }
            } catch (Exception e) {
                //导入失败
                importFailIdList.add(i+2);
                ifImportError = "1";
                log.error("ContractImportServiceImpl contractImport error:", e);
                Boolean result = importFailureLogDbService.selectImportFailureLogByExample("4",contractNumber,companyId,accountId,contractImportVO != null ? contractImportVO.toString() : "");
                if(!result){
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, contractImportVO, "4", "合同表第" +(i+2)+ "行，合同编号:" + contractImportVO.getContractNumber() + "，插入数据失败",null,getExceptionPrintStackTrace(e),"2",companyId,accountId));
                }
                e.printStackTrace();
            }
            end.countDown();
        }

        JSONObject result = new JSONObject();
        result.put("importNum",importNum);
        result.put("customerEmptyIdList",customerEmptyIdList);
        result.put("customerNotExistIdList",customerNotExistIdList);
        result.put("repeatIdList",repeatIdList);
        result.put("ownerEmptyIdList",ownerEmptyIdList);
        result.put("importFailIdList",importFailIdList);
        result.put("notValidIdList",notValidIdList);
        return result;
    }

    public CustomerContract addContractModel(ContractImportVO contractImportVO,Customer customer,UserInfo userInfo,String importError) throws ParseException {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(CommonUtils.getGUID());
        customerContract.setCreateTm(dateTime.parse(contractImportVO.getCreateTm()));
        if(customer!=null){
            customerContract.setCustomerId(customer.getCustomerId());
            customerContract.setCustomerName(customer.getCustomerName());
        }
        customerContract.setContractNumber(contractImportVO.getContractNumber());
        customerContract.setMasterMembershipContract(contractImportVO.getMasterMembershipContract());
        if("否".equals(contractImportVO.getWhetherHang())){
            customerContract.setWhetherHang("0");
        }else if("是".equals(contractImportVO.getWhetherHang())){
            customerContract.setWhetherHang("1");
        }
        customerContract.setAdvancePostponementReason(contractImportVO.getAdvancePostponementReason());
        //不知道邮箱是什么邮箱
        //customerContract.setCustomerEmail(contractImportVO.getCustomerEmail());

        //联系人(用客户id、联系人名称、联系人电话统一查询)
        if(!StringUtils.isBlank(contractImportVO.getContact())){
            if(customer!=null){
                Contact contact = contactDbService.getContactByCustomerIdAndContactName(customer.getCustomerId(),contractImportVO.getContact());
                if(contact!=null){
                    customerContract.setContactId(contact.getContactId());
                    customerContract.setContactName(contact.getContactName());
                    customerContract.setContactDetails(contact.getContactInformation());
                }
            }
        }
        //合同状态生效中
        if("未生效".equals(contractImportVO.getContractStatus())){
            customerContract.setContractStatus("1");
        }else if("生效中".equals(contractImportVO.getContractStatus())){
            customerContract.setContractStatus("2");
        }else if("已结束".equals(contractImportVO.getContractStatus())){
            customerContract.setContractStatus("3");
        }else if("已作废".equals(contractImportVO.getContractStatus())){
            customerContract.setContractStatus("4");
        }else if("意外终止".equals(contractImportVO.getContractStatus())){
            customerContract.setContractStatus("5");
        }

        //合同类型新单合同
        if("会员新单合同".equals(contractImportVO.getContractType())){
            customerContract.setContractType("2");
        }else if("续费合同".equals(contractImportVO.getContractType())){
            customerContract.setContractType("4");
        }
        //是老合同
        customerContract.setOldContract("1");
        if(contractImportVO.getContractStartDate()!=null){
            customerContract.setContractStartDate(date.parse(contractImportVO.getContractStartDate()));
        }
        if(contractImportVO.getContractEndDate()!=null){
            customerContract.setContractEndDate(date.parse(contractImportVO.getContractEndDate()));
        }

        //合同实际成交金额
        if(contractImportVO.getContractReceivables()!=null){
            customerContract.setContractReceivables(new BigDecimal(contractImportVO.getContractReceivables()));
        }

        //合同实际总金额
        if(contractImportVO.getContractActualTotalAmount()!=null){
            customerContract.setContractActualTotalAmount(new BigDecimal(contractImportVO.getContractActualTotalAmount()));
        }
        //合同总金额
        if(contractImportVO.getContractTotalPaymentAmount()!=null){
            customerContract.setContractTotalPaymentAmount(new BigDecimal(contractImportVO.getContractTotalPaymentAmount()));
        }
        //合同优惠总金额
        if(contractImportVO.getContractDiscountTotalAmount()!=null){
            customerContract.setContractDiscountTotalAmount(new BigDecimal(contractImportVO.getContractDiscountTotalAmount()));
        }

        //是否合作开发
        if("是".equals(contractImportVO.getWhetherCooperateDevelopment())){
            customerContract.setWhetherCooperateDevelopment("1");
        }else if("否".equals(contractImportVO.getWhetherCooperateDevelopment())){
            customerContract.setWhetherCooperateDevelopment("0");
        }


        //所属分公司
        if(userInfo!=null){
            customerContract.setAffiliationCompanyId(userInfo.getCompanyId());
            //所有人
            customerContract.setCreatePeopleId(userInfo.getAccountId());
            //更新人
            customerContract.setUpdatePeopleId(userAccount.getAccountId());
        }else{
            SysCompany sysCompany = companyDbService.selectSysCompanyByName(contractImportVO.getCompanyName());
            customerContract.setAffiliationCompanyId(sysCompany.getCompanyId());
        }
        //会员分类(导入的合同都是会员合同)
        customerContract.setWhetherCheck("1");
        //支付方式
        if("线下支付".equals(contractImportVO.getPaymentMethod())){
            customerContract.setPaymentMethod("2");
        }else if("余额支付".equals(contractImportVO.getPaymentMethod())){
            customerContract.setPaymentMethod("3");
        }
        //合同总金额
        if(contractImportVO.getContractTotalAmount()!=null){
            customerContract.setContractTotalAmount(new BigDecimal(contractImportVO.getContractTotalAmount()));
        }
        //提成发放状态
        if("已全部发放".equals(contractImportVO.getCommissionStatus())){
            customerContract.setCommissionStatus("1");
        }else if("已部分发放".equals(contractImportVO.getCommissionStatus())){
            customerContract.setCommissionStatus("2");
        }else if("未发放".equals(contractImportVO.getCommissionStatus())){
            customerContract.setCommissionStatus("3");
        }

        //合同续费
        if("正常合同".equals(contractImportVO.getContractRenewal())){
            customerContract.setContractRenewal("1");
        }else if("提前续费".equals(contractImportVO.getContractRenewal())){
            customerContract.setContractRenewal("2");
        }else if("延期续费".equals(contractImportVO.getContractRenewal())){
            customerContract.setContractRenewal("3");
        }

        //合同分类先算到合同入口中
        customerContract.setContractCategory(0);
        //删除状态
        customerContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        customerContract.setPaymentStatus("1");
        //更新时间设置为导入合同的时间
        customerContract.setUpdateTm(new Date());

        customerContract.setImportError(importError);
        customerContract.setPaymentNumber(1);

        return customerContract;
    }

    /**
     * 获取导入失败日志
     * @Author lj
     * @Date  2021/6/2 8:59
     * @param accountId 账号ID
     * @param contractImportVO 订单信息
     * @param operateType 导入什么业务：4-合同
     * @param reasonForFailure 失败原因
     * @param dataId 重复数据ID:客户ID/订单ID
     * @param exceptionLog 异常日志
     * @param logType 日志类型：1-重复日志；2.异常日志
     * @return {@link {com.crm.model.entity.sys.ImportFailureLog}}
     */
    private ImportFailureLog getImportFailureLog(String operatePeopleId, ContractImportVO contractImportVO,
                                                 String operateType, String reasonForFailure, String dataId,
                                                 String exceptionLog, String logType,String companyId,String accountId) {
        ImportFailureLog importFailureLog = new ImportFailureLog();
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(operatePeopleId);
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType(operateType);
        importFailureLog.setImportName(contractImportVO != null ? contractImportVO.getContractNumber(): "");
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(contractImportVO != null ? contractImportVO.toString() : "");
        importFailureLog.setDataId(dataId);
        importFailureLog.setExceptionLog(exceptionLog);
        importFailureLog.setLogType(logType);
        importFailureLog.setCompanyId(companyId);
        importFailureLog.setAccountId(accountId);
        return importFailureLog;
    }

    /**
     * 获取异常信息
     * @Author pym
     * @Date  2021/5/27 16:05
     * @param e 异常
     * @return {@link {java.lang.String}}
     */
    private static String getExceptionPrintStackTrace(Exception e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
}
